<?php
/**
 * Each engineer has a duty to keep the code elegant
 * Created by wolffy.
 * Author @wolffy<13750088090@sina.cn>
 * Date: 2018/8/11
 * Time: 22:46
 */
namespace App\Services;

use App\Handlers\ApiResponse;
use App\Repositories\PassageRepository;
use App\Repositories\ThreeApiErrorLogsRepository;
use App\Repositories\UserCreditCardRepository;
use App\Repositories\UserPassageRegisterRepository;
use App\Repositories\UserPassageRepository;
use App\Services\LandingRepaymentC\LandingRepaymentCService;
use App\Services\LandingRepaymentE\LandingRepaymentEService;
use App\Services\RepaymentPay\LandingPayCService;
use App\Services\RepaymentPay\LargePayXService;

class UserPassageService
{
    use ApiResponse;

    protected $passageRepository;
    protected $userPassageRepository;
    protected $userCreditCardRepository;
    protected $threeApiErrorLogsRepository;
    protected $userPassageRegisterRepository;
    protected $landingRepaymentCService;
    protected $landingRepaymentEService;
    protected $landingPayCService;
    protected $largePayXService;

    public function __construct(PassageRepository $passageRepository,
                                UserPassageRepository $userPassageRepository,
                                UserCreditCardRepository $userCreditCardRepository,
                                ThreeApiErrorLogsRepository $threeApiErrorLogsRepository,
                                UserPassageRegisterRepository $userPassageRegisterRepository,
                                LandingRepaymentCService $landingRepaymentCService,
                                LandingRepaymentEService $landingRepaymentEService,
                                LandingPayCService $landingPayCService,
                                LargePayXService $largePayXService)
    {
        $this->passageRepository = $passageRepository;
        $this->userPassageRepository = $userPassageRepository;
        $this->userCreditCardRepository = $userCreditCardRepository;
        $this->threeApiErrorLogsRepository = $threeApiErrorLogsRepository;
        $this->userPassageRegisterRepository = $userPassageRegisterRepository;
        $this->landingRepaymentCService = $landingRepaymentCService;
        $this->landingRepaymentEService = $landingRepaymentEService;
        $this->landingPayCService = $landingPayCService;
        $this->largePayXService = $largePayXService;
    }

    /**
     * 用户是否拥有子商户号
     * @param $user
     * @param $cardId
     * @param $passageId
     * @return \Illuminate\Http\JsonResponse
     */
    public function isHasSubMerchantRegister($user, $cardId, $passageId)
    {
        //通道id 用户id查找是否有子商户号
        $userPassageMerchantNo = $this->userPassageRepository->getSubMerchantNo($passageId, $user['user_id']);
        if (empty($userPassageMerchantNo)) {
            if ($passageId == 1) {
                $subMerchantRegisterSmallAmount = $this->subMerchantRegisterSmallAmount($cardId, $user, $passageId);
                return $subMerchantRegisterSmallAmount;
            }
            if ($passageId == 3) {
                $subMerchantRegisterLargeAmount = $this->subMerchantRegisterLargeAmount($cardId, $user, $passageId);
                return $subMerchantRegisterLargeAmount;
            }
        }
        return $userPassageMerchantNo;
    }

    /**
     * 小额c注册子商户
     * @param $cardId
     * @param $user
     * @param $passageId
     * @return \Illuminate\Http\JsonResponse
     */
    public function subMerchantRegisterSmallAmount($cardId, $user, $passageId)
    {
        $card = $this->userCreditCardRepository->validateCreditCardIsUser($cardId, $user['user_id']);
        if (empty($card)) {
            return $this->responseJson(10306);//信用卡不存在
        }
        //注册子商户号
        $orderNo = makeOrderNo();
        $result = $this->landingPayCService->subMerchantRegister($orderNo, $user['realname'], $user['idcard_number'], $card->bank_no, $card->bank_mobile);
        $errorData = [
            'order_no' => $orderNo,
            'error_code' => $result['response']['code'],
            'error_msg' => json_encode($result),
            'api_type' => 1
        ];
        $this->threeApiErrorLogsRepository->create($errorData);
        if ($result['response']['code'] == 0) {
            $this->userPassageRepository->create([
                'passage_id' => $passageId,
                'user_id' => $user['user_id'],
                'sub_merchant_no' => $result['response']['data']['sub_mch_no'],
            ]);
            return $result['response']['data']['sub_mch_no'];
        } else {
            return $this->responseJson(10509, [], false, $result['response']['message'], $result['response']['message']);//创建子商户号出错
        }
    }

    /**
     * 大额e注册子商户
     * @param $cardId
     * @param $user
     * @param $passageId
     * @return \Illuminate\Http\JsonResponse
     */
    public function subMerchantRegisterLargeAmount($cardId, $user, $passageId)
    {
        $card = $this->userCreditCardRepository->validateCreditCardIsUser($cardId, $user['user_id']);
        if (empty($card)) {
            return $this->responseJson(10306);//信用卡不存在
        }
        //注册子商户号
        $orderNo = makeOrderNo();
        $result = $this->largePayXService->subMerchantRegister($orderNo, $user['realname'], $user['idcard_number']);
        $errorData = [
            'order_no' => $orderNo,
            'error_code' => $result['response']['code'],
            'error_msg' => json_encode($result),
            'api_type' => 16
        ];
        $this->threeApiErrorLogsRepository->create($errorData);
        if ($result['response']['code'] == 0) {
            $this->userPassageRepository->create([
                'passage_id' => $passageId,
                'user_id' => $user['user_id'],
                'sub_merchant_no' => $result['response']['data']['sub_mch_no'],
            ]);
            return $result['response']['data']['sub_mch_no'];
        } else {
            return $this->responseJson(10509, [], false, $result['response']['message'], $result['response']['message']);//创建子商户号出错
        }
    }

    /**
     * 子商户是否开卡
     * @param $user
     * @param $cardId
     * @param $passageId
     * @return \Illuminate\Http\JsonResponse
     */
    public function isHasSubMerchantOpenCard($user, $cardId, $passageId, $subMerchantNo, $expireDate, $cvn2)
    {
        //根据信用卡id获取信用卡信息
        $card = $this->userCreditCardRepository->validateCreditCardIsUser($cardId, $user['user_id']);
        if (empty($card)) {
            return $this->responseJson(10306);//信用卡不存在
        }
        $orderNo = makeOrderNo();
        $returnUrl = config('pay.fourpay.landing_pay_c.bind_card_return_url') .
            '?flag=own&code=SUCCESS&order_no=' . $orderNo;
        $isOpenCard = $this->userPassageRegisterRepository->isOpenCard($passageId, $user['user_id'], $cardId);
        if (empty($isOpenCard) || $isOpenCard->is_open == 0) {
            $result = $this->landingPayCService->subMerchantBindCard($orderNo, $subMerchantNo, $card->bank_code,
                $card->bank_no, $card->bank_mobile, $expireDate, $cvn2, $returnUrl);;
            $errorData = [
                'order_no' => $orderNo,
                'error_code' => $result['response']['code'],
                'error_msg' => json_encode($result),
                'api_type' => 2
            ];
            if ($result['response']['code'] == 0) {
                //子商户绑卡
                $this->userPassageRegisterRepository->create([
                    'order_no' => $orderNo,
                    'passage_id' => $passageId,
                    'user_id' => $user['user_id'],
                    'card_id' => $cardId,
                    'is_bind' => 1,
                    'is_open' => 0,
                ]);
                $this->threeApiErrorLogsRepository->create($errorData);
                $data['success_jump_url'] = $result['response']['data']['pay_return_url'];
                if (isset($result['response']['data']['pay_url'])) {
                    $data['open_card_url'] = $result['response']['data']['pay_url'];
                } else {
                    $data['open_card_html'] = $result['response']['data']['pay_html'];
                }
                return $this->responseJson(10510, $data);
            } else {
                $this->threeApiErrorLogsRepository->create($errorData);
                return $this->responseJson(422, [], false, $result['response']['message'], $result['response']['message']);//创建子商户号出错
            }
        } else if ($isOpenCard->is_open == 2) {
            return $this->responseJson(10514);//交易卡开通中,请稍等
        } else {
            return  true;
        }
    }
}